<template>
  <div>
    <el-card>
      <div class="noptice-header flex items-center justify-between">
        <el-button type="primary" size="small" @click="createClick"
          >新增</el-button
        >
        <el-button type="primary" size="small" @click="getData">
          <el-icon>
            <Refresh />
          </el-icon>
        </el-button>
      </div>
      <el-table :data="tableList">
        <el-table-column prop="name" label="优惠券名称" width="300px">
          <template #default="{ row }">
            <div
              class="coupon bg-light-300 py-2 px-4"
              :class="row.statusText === '领取中' ? 'active ' : 'inactive'"
            >
              <p class="font-bold text-md">{{ row.name }}</p>
              <span>{{ row.create_time }} - {{ row.end_time }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="statusText" label="状态"></el-table-column>
        <el-table-column prop="title" label="优惠">
          <template #default="{ row }">
            <span v-if="row.type === 0"
              >满 {{ row.min_price }}减{{ Number(row.value).toFixed(0) }}
            </span>
            <span v-else>
              满 {{ row.min_price }}打{{
                Number(row.value).toFixed(0)
              }}
              折</span
            >
            <!-- 满 min_price -  value -->
          </template>
        </el-table-column>
        <el-table-column prop="total" label="发放数量"></el-table-column>
        <el-table-column prop="used" label="已使用"></el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <div v-if="scope.row.statusText === '领取中'">
              <el-button
                type="warning"
                plain
                size="small"
                @click="invalidClick(scope.row)"
                >失效</el-button
              >
            </div>
            <div v-else>
              <el-button
                text
                type="primary"
                size="small"
                @click="editNoticeClick(scope.row)"
                >修改</el-button
              >
              <el-popconfirm
                title="是否要删除该优惠吗？"
                confirmButtonText="确认"
                cancelButtonText="取消"
                @confirm="handleDelete(scope.row.id)"
              >
                <template #reference>
                  <el-button text type="danger" size="small">删除</el-button>
                </template>
              </el-popconfirm>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div class="flex items-center justify-center mt-3">
        <el-pagination
          background
          layout="prev, pager,next"
          :total="total"
          :current-page="page"
          :page-size="limit"
          @current-change="changePage"
        />
      </div>
    </el-card>

    <Drawer
      ref="DrawerRef"
      :title="title === 'add' ? '添加公告' : '修改公告'"
      @submit="submit"
    >
      <el-form
        ref="formRef"
        :model="fromData"
        label-width="100px"
        :rules="rules"
      >
        <el-form-item label="优惠券名称" prop="title">
          <el-input v-model="fromData.name" placeholder="请输入优惠券名称" />
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-radio-group v-model="fromData.type" size="small">
            <el-radio :label="0" border>满减</el-radio>
            <el-radio :label="1" border>折扣</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="面值" prop="title">
          <el-input v-model="fromData.value" placeholder="请输入优惠券面值">
            <template #append>{{ fromData.type === 0 ? "元" : "折" }}</template>
          </el-input>
        </el-form-item>
        <el-form-item label="发行数量" prop="title">
          <el-input-number v-model="fromData.total" :min="1" :max="100" />
        </el-form-item>
        <el-form-item label="最低使用" prop="title">
          <el-input
            v-model="fromData.min_price"
            placeholder="请输入最低使用多少元"
          >
            <template #append>元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="排序" prop="title">
          <el-input-number v-model="fromData.order" :min="1" :max="100" />
        </el-form-item>
        <el-form-item label="活动时间" prop="title">
          <el-date-picker
            v-model="timerange"
            type="datetimerange"
            value-format="YYYY-MM-DD HH:mm:ss"
            range-separator="To"
            start-placeholder="Start date"
            end-placeholder="End date"
          />
        </el-form-item>
        <el-form-item label="描述" prop="content">
          <el-input
            v-model="fromData.desc"
            placeholder="请输入描述内容"
            type="textarea"
          ></el-input>
        </el-form-item>
      </el-form>
    </Drawer>
  </div>
</template>

<script setup>
import { computed } from "vue";
import Drawer from "@/components/Drawer/index.vue";
import { Toast } from "@/utils/utils";
import {
  getCouponrList,
  delCouponr,
  addCouponr,
  editCoupon,
  invalidCouponr,
} from "@/api/coupon";
import { useInitTable, useInitForm } from "@/composables/useCommon.js";
function formatStatus(row) {
  let s = "领取中";
  let start_time = new Date(row.start_time).getTime();
  let now = new Date().getTime();
  let end_time = new Date(row.end_time).getTime();
  if (start_time > now) {
    s = "未开始";
  } else if (end_time < now) {
    s = "已结束";
  } else if (row.status == 0) {
    s = "已失效";
  }
  return s;
}
const { tableList, page, total, limit, getData, changePage, handleDelete } =
  useInitTable({
    getList: getCouponrList,
    del: delCouponr,

    onGetListSuccess: (res) => {
      tableList.value = res.data.list.map((o) => {
        // 转化优惠券状态
        o.statusText = formatStatus(o);
        return o;
      });
      total.value = res.data.totalCount;
    },
  });

const {
  fromData,
  title,
  formRef,
  rules,
  DrawerRef,
  createClick,
  submit,
  editNoticeClick,
} = useInitForm({
  fromData: {
    name: "",
    type: 0, //类型：0满减,1折扣
    value: 0,
    total: 20,
    min_price: 0,
    start_time: "",
    end_time: "",
    order: 50,
    desc: "",
  },
  create: addCouponr,
  updata: editCoupon,
  getData: getData,
  rules: {
    // title: [{ required: true, message: "请输入公告标题", trigger: "blur" }],
    // content: [{ required: true, message: "请输入公告内容", trigger: "blur" }],
  },
  beforeSubmit: (f) => {
    if (typeof f.start_time != "number") {
      f.start_time = new Date(f.start_time).getTime();
    }
    if (typeof f.end_time != "number") {
      f.end_time = new Date(f.end_time).getTime();
    }
    return f;
  },
});
const timerange = computed({
  get() {
    return fromData.start_time && fromData.end_time
      ? [fromData.start_time, fromData.end_time]
      : [];
  },
  set(val) {
    fromData.start_time = val[0];
    fromData.end_time = val[1];
  },
});
// 失效
const invalidClick = (row) => {
  invalidCouponr(row.id).then((res) => {
    if (res.data) {
      Toast("优惠券已成功失效");
      getData();
    }
  });
};
</script>

<style lang="scss">
.coupon {
  span {
    font-size: 12px;
  }
}
.active {
  @apply border-rose-200 bg-rose-50 text-red-400;
}
.inactive {
  @apply border-gray-200 bg-gray-50 text-gray-400;
}
</style>
